package org.yzh.rbac.service;

import org.sample.commons.lang.JWTUtils;
import org.sample.commons.lang.StrUtils;
import org.sample.model.exception.APIException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzh.rbac.component.Constant;
import org.yzh.rbac.component.PermisUtils;
import org.yzh.rbac.mapper.UserMapper;
import org.yzh.rbac.model.entity.UserDO;
import org.yzh.rbac.model.enums.ResultCodes;
import org.yzh.rbac.model.vo.Permis;
import org.yzh.rbac.model.vo.Token;
import org.yzh.rbac.model.vo.User;

import java.util.List;
import java.util.Set;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermisService permisService;

    public List<UserDO> find(UserDO entity) {
        List<UserDO> result = userMapper.find(entity);
        return result;
    }

    public User login(String username, String password) {
        UserDO user = userMapper.getByUsername(username);

        if (user == null)
            throw new APIException(ResultCodes.NotFoundUser);
        if (!user.getPassword().equals(password))
            throw new APIException(ResultCodes.UsernameOrPasswordError);

//        int[] roles = StrUtils.toInts(user.getRoles(), ",");
//        Set<Permis> permisSet = permisService.findByRoleId(roles);
//        List<Permis> permisTree = PermisUtils.toTree(permisSet);

        User result = new User();
        result.setId(user.getId());
        result.setUsername(username);
        result.setRoleList(null);
//        result.setPermisTree(permisTree);

        Token token = new Token();
        token.setId(user.getId());
        token.setUsername(username);
//        token.setRoles(roles);

        String tokenStr = JWTUtils.sign(token, Constant.TokenExpiry);
        result.setAccessToken(tokenStr);

        return result;
    }

    public UserDO get(Integer id) {
        UserDO result = userMapper.get(id);
        return result;
    }

    public int add(UserDO entity) {
        int row = userMapper.insert(entity);
        return row;
    }

    public int update(UserDO entity) {
        int row = userMapper.update(entity);
        return row;
    }

    public int delete(Integer id) {
        int row = userMapper.delete(id);
        return row;
    }
}